package com.howie.hmvc.paramparse;

import java.lang.annotation.Annotation;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;

import com.howie.hmvc.annotations.Valid;
import com.howie.hmvc.exception.ArguErrorException;
import com.howie.hmvc.request.MultipartRequest;

public class ParamFile extends AbsParamParse {

	private boolean isValid;
	private boolean required;
	private double minLength;
	private double maxLength;
	private String[] allowType;
	
	@Override
	public void init(Annotation[] an) throws Exception {
		Valid valid = getValid(an);
		if(valid != null){
			isValid = true;
			required = valid.required();
			minLength = valid.minLength();
			maxLength = valid.maxLength();
			allowType = valid.allowType();
		}
	}
	
	@Override
	public Object getParamter(HttpServletRequest request,HttpServletResponse response) throws Exception{
		if(!(request instanceof MultipartRequest)){
			throw new Exception("上传文件的表单不是'multipart/form-data'表单");
		}
		MultipartRequest mpReq = (MultipartRequest)request;
		FileItem val = mpReq.getFile(name);
		if(isValid){
			if(val == null){
				if(required){
					throw new ArguErrorException(name,"required",null);
				}
			}else{
				if(val.getSize() < minLength){
					throw new ArguErrorException(name,"minLength",minLength);
				}
				if(val.getSize() > maxLength){
					throw new ArguErrorException(name,"maxLength",maxLength);
				}
				if(allowType.length > 0){
					String fileName = val.getName().toLowerCase();
					boolean allow = false;
					for(String type : allowType){
						if(fileName.endsWith("."+type.toLowerCase())){
							allow = true;
							break;
						}
					}
					if(!allow){
						throw new ArguErrorException(name,"allowType",StringUtils.join(allowType,","));
					}
				}
			}
		}
		return val;
	}
}
